package com.agileai.portal.controller.uui;

import java.util.Date;

import com.agileai.common.AppConfig;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.RedirectRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.SecurityAuthorizationConfig;
import com.agileai.portal.bizmoduler.auth.SecurityGroupManage;
import com.agileai.portal.bizmoduler.uui.UserLocalManage;
import com.agileai.portal.extend.uui.UserSyncHelper;
import com.agileai.portal.wsclient.uui.ResultStatus;
import com.agileai.portal.wsclient.uui.UserSync;
import com.agileai.util.CryptionUtil;
import com.agileai.util.DateUtil;
import com.agileai.util.StringUtil;

public class ResetPasswordHandler
        extends BaseHandler {
	
    public ResetPasswordHandler() {
        super();
        this.serviceId = buildServiceId(SecurityGroupManage.class);
    }

	public ViewRenderer prepareDisplay(DataParam param){
		String userId = param.get("userId");
		String tokeId = param.get("tokenId");
		this.setAttributes(param);
		if (StringUtil.isNotNullNotEmpty(userId)){
			UserLocalManage userLocalManage = this.lookupService(UserLocalManage.class);
			DataRow row  = userLocalManage.retrieveUserRecord(userId);
			if (row != null && !row.isEmpty()){
				AppConfig appConfig = (AppConfig)this.lookupService("appConfig");
				String tempTokenId = row.getString("TOKEN_ID");
				if (tempTokenId != null && tempTokenId.equals(tokeId)){
					Date date = row.getTimestamp("TOKEN_TIME");
					Date curDate = new Date();
					long diffDay = DateUtil.getDateDiff(date, curDate, DateUtil.DAY);
					int ExpiredDays = appConfig.getIntConfig("UnifiedUserIntegrateConfig", "ExpiredDays");
					if (diffDay > ExpiredDays){
						if (resetToken8SendMail(row)){
							String mail = row.getString("USER_MAIL");
							this.setAttribute("message","密码重置URL已过期，生成新密码重置链接发至邮箱"+UserSyncHelper.genMaskedMail(mail));
						}else{
							this.setAttribute("message","密码重置URL已过期，生成新密码重置链接失败！");
						}
					}
				}else{
					this.setAttribute("message","不合法的密码重置URL，请检查!");		
				}
			}else{
				this.setAttribute("message",userId + "用户不存在,请确认!");
			}
		}else{
			this.setAttribute("message","密码重置链接以及参数不正确,请检查!");
		}
		return new LocalRenderer(getPage());
	}    

	@PageAction
	public ViewRenderer showResult(DataParam param){
		String result = param.get("result");
		this.setAttributes(param);
		if ("success".equals(result)){
			AppConfig appConfig = (AppConfig)this.lookupService("appConfig");
			String activeRedirectURL = appConfig.getConfig("UnifiedUserIntegrateConfig", "ActiveRedirectURL");
			this.setAttribute("activeRedirectURL",activeRedirectURL);
		}else{
			this.setErrorMsg("修改密码失败,请检查重新操作!");
		}
		return new LocalRenderer(getPage());
	}  
	
	private boolean resetToken8SendMail(DataRow row){
		boolean result = false;
		try {
			UserSync userSync = UserSyncHelper.getUserSyncService();
			String tokenId = UserSyncHelper.genTokenId("sendMail");
			String mailAddress = row.stringValue("USER_MAIL");
			String userCode = row.stringValue("USER_CODE");
			String storeTokenId = String.valueOf(System.currentTimeMillis());
			String mailContent = UserSyncHelper.createFindPwdMailContent(userCode, storeTokenId);
			String mailSubject = "密码重置链接";
			ResultStatus resultStatus = userSync.sendMail(tokenId, mailAddress,mailSubject,mailContent);
			if (resultStatus.isSuccess()){
				Date storeTokenTime = new Date();
				UserLocalManage userLocalManage = this.lookupService(UserLocalManage.class);
				userLocalManage.updateUserTokends(userCode, storeTokenId, storeTokenTime);
				result = true;				
			}
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
		return result;
	}	
	
	private boolean resetPassword(String userId,String userPwd){
		boolean result = false;
		try {
			UserSync userSync = UserSyncHelper.getUserSyncService();
			String tokenId = UserSyncHelper.genTokenId("modifyPassword");
			ResultStatus resultStatus = userSync.modifyPassword(tokenId, userId, userPwd);
			if (resultStatus.isSuccess()){
				SecurityAuthorizationConfig authorizationConfig = this.lookupService(SecurityAuthorizationConfig.class);
				String encryptPwd = CryptionUtil.md5Hex(userPwd);
				authorizationConfig.modifyUserPassword(userId, encryptPwd);
				
				Date storeTokenTime = new Date();
				UserLocalManage userLocalManage = this.lookupService(UserLocalManage.class);
				userLocalManage.updateUserTokends(userId, "", storeTokenTime);
				result = true;				
			}
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
		return result;
	}	
    
    @PageAction
	public ViewRenderer resetPassword(DataParam param){
		String userCode = param.get("USER_CODE");
		String userPassword = param.get("USER_PWD");
		String url = null;
		if (resetPassword(userCode,userPassword)){
			url = getHandlerURL()+"&actionType=showResult&userId="+userCode+"&result=success";
		}else{
			url = getHandlerURL()+"&actionType=showResult&userId="+userCode+"&result=failure";
		}
		return new RedirectRenderer(url);
	}
}